﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace H2.NET.DBUtility
{
    public static class BulkCopyHelper
    {
        /// <summary>
        /// 批量导入数据到数据库
        /// </summary>
        /// <param name="table">数据源表</param>
        /// <param name="tableName">数据库表名</param>
        /// <param name="connStr">数据库连接字符串</param>
        /// <param name="mappings">源表与数据库表的列映射关系</param>
        public static void BulkCopyDataTable(DataTable table, string tableName, string connStr, params SqlBulkCopyColumnMapping[] mappings)
        {
            //使用SqlBulkCopy来批量导入数据到数据库
            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(connStr))
            {
                //写出数据库中的目标表名
                bulkcopy.DestinationTableName = tableName;
                //建立数据源与数据库之间列的映射，就是要让SqlBulkCopy知道你要把哪一列插到哪一列
                foreach (SqlBulkCopyColumnMapping mapping in mappings)
                {
                    //也可以通过bulkcopy.ColumnMappings.Add("数据源列名", "数据表列名");
                    bulkcopy.ColumnMappings.Add(mapping);
                }
                //将数据提交到数据库中
                bulkcopy.WriteToServer(table);
            }
        }

    }
}
